from fastapi import APIRouter, Query, UploadFile
from tortoise.expressions import Q
from app.settings import settings
from app.controllers.customer.users import users_controller
from app.controllers.orders.list import orders_list_controller
from app.models import OrdersList, Coupons, CouponsRole
from app.schemas.base import Success, SuccessExtra, Fail
from app.schemas.orders import *
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from datetime import datetime

mini_orders_list_router = APIRouter()
model_name = "订单"


@mini_orders_list_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_orders_list_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        is_express: int = Query(-1, description="发货状态"),
        is_review: int = Query(0, description="是否评价"),
        status: int = Query(-1, description="订单状态"),
        type: int = Query(0, description="订单类型"),
        type2: int = Query(1, description="1当前2历史"),
):
    # 获取今天的日期并将时间设为00:00:00
    today_start = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
    user_id = CTX_USER_ID.get()
    q = Q(user_id=user_id)

    if status > -1:
        q &= Q(status=status)
    if is_express > -1:
        q &= Q(is_express=is_express)
    if type > -1:
        q &= Q(type=int(type + 1))
    if is_review > -1:
        q &= Q(is_review=is_review)
    # 根据 type2 参数来查询今天的订单或今天之前的订单
    if type2 == 1:  # 今天的订单
        q &= Q(created_at__gte=today_start)  # created_at >= 今天零点
    elif type2 == 2:  # 今天之前的订单
        q &= Q(created_at__lt=today_start)  # created_at < 今天零点

    total, data = await orders_list_controller.do_list(page=page, page_size=page_size, search=q)
    print(total, data)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@mini_orders_list_router.get("/get", summary=f"查看{model_name}详情", dependencies=[DependCustomerAuth])
async def do_orders_list_get(
        data_id: int = Query(..., description="ID"),
):
    user_id = CTX_USER_ID.get()
    data = await orders_list_controller.do_detail(data_id=data_id, user_id=user_id)
    ##如果未付款状态需要返回可用的充值金和优惠券数量
    if data["status"] == 0:
        deposit = await users_controller.update_money(type=1, user_id=user_id)
        data["deposit"] = deposit
        order_price = data["price"]
        user_coupons = await Coupons.filter(user_id=user_id).filter(is_used=0).all().values("id", "coupons_id",
                                                                                            "coupons_price",
                                                                                            "expire_at")
        coupon_ids = [coupon['coupons_id'] for coupon in user_coupons]
        coupon_roles = await CouponsRole.filter(id__in=coupon_ids).all()
        coupon_roles_dict = {role.id: role for role in coupon_roles}
        can_coupons = []
        if data['type'] != 3:
            for coupon in user_coupons:
                coupon_role = coupon_roles_dict.get(coupon['coupons_id'])
                if coupon_role and order_price >= coupon_role.role:
                    coupon['name'] = coupon_role.name
                    coupon['active'] = False
                    if coupon['expire_at']:
                        coupon['expire_at'] = coupon['expire_at'].strftime('%Y-%m-%d')
                    else:
                        coupon['expire_at'] = None
                    can_coupons.append(coupon)
        data["can_coupons"] = can_coupons
    data["status_name"] = settings.ORDERS_STATUS[data["status"]]
    return Success(data=data)


@mini_orders_list_router.post("/create", summary=f"创建{model_name}", dependencies=[DependCustomerAuth])
async def do_orders_list_create(
        data_in: OrdersListCreateMini,
):
    user_id = CTX_USER_ID.get()
    ret = await orders_list_controller.do_create(obj_in=data_in, user_id=user_id)
    if ret["pay_status"] == 1:
        return Success(msg="下单成功", data=ret)
    else:
        return Fail(msg=ret["msg"])


@mini_orders_list_router.post("/express_price", summary=f"获取运费", dependencies=[DependCustomerAuth])
async def express_price(
        data_in: OrdersListUpdateExpress,
):
    user_id = CTX_USER_ID.get()
    await orders_list_controller.get_express_price(order_id=data_in.order_id, receive_id=data_in.receive_id)
    return Success(msg="更新运费成功")


@mini_orders_list_router.post("/update", summary=f"编辑订单收货信息和备注")
async def do_orders_update(
        data_in: OrdersListUpdateMini,
):
    await OrdersList.filter(id=data_in.id).update(remark=data_in.remark)
    return Success(msg="更新成功")


@mini_orders_list_router.post("/update_review", summary=f"编辑订单评分以及评价")
async def do_orders_update(
        data_in: OrdersListUpdateEvaluation,
):
    await OrdersList.filter(id=data_in.id).update(order_rate=data_in.order_rate,
                                                  order_evaluations=data_in.order_evaluations,
                                                  is_review=1)
    return Success(msg="更新成功")


@mini_orders_list_router.post("/pay", summary=f"支付订单")
async def do_pay(
        data_in: OrdersListPay,
):
    ret = await orders_list_controller.order_pay(data_in=data_in)
    if ret["pay_status"] == 1:
        return Success(msg="支付成功", data=ret)
    else:
        return Fail(msg=ret["msg"])


@mini_orders_list_router.get("/delete", summary="取消订单/申请退款", dependencies=[DependCustomerAuth])
async def do_orders_list_delete(
        data_id: int = Query(..., description="ID"),
        status: int = Query(..., description="2取消订单3申请退款"),
):
    user_id = CTX_USER_ID.get()
    # can = await orders_list_controller.do_can_edit(data_id=data_id)
    # if not can:
    #     return JSONResponse(content={"code": 400, "message": "该订单已经付款，无法删除"}, status_code=200)
    await orders_list_controller.do_delete(data_id=data_id, user_id=user_id, status=status)
    return Success(msg="删除成功")
